package cn.charmaine.org.controller;

import cn.charmaine.basic.util.AjaxResult;
import cn.charmaine.basic.util.PageList;
import cn.charmaine.org.domain.Employee;
import cn.charmaine.org.query.EmployeeQuery;
import cn.charmaine.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/emp")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    /**
     * 查询所有的管理员
     * @return
     */
    @GetMapping
    public List<Employee> queryEmployeeAll(){
        return employeeService.queryAll();
    }

    /**
     * 根据id查询
     *
     * @GetMapping 请求方式为get http://localhost:8080/dept/1
     * @ApiParam(name="编号",required = true) 为true必须传值
     */
    //@RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @GetMapping("/{id}")
    public Employee queryById(@PathVariable("id") Long id) {
        return employeeService.queryById(id);
    }

    /**
     * 分页查询
     *
     * @PostMapping 请求方式为post http://localhost:8080/dept
     * @RequestBody 请求体  接收客户端发送的json格式数据
     */
    @PostMapping
    public PageList<Employee> queryByPage(@RequestBody EmployeeQuery query) {
        return employeeService.queryData(query);
    }

    /**
     * 添加或者修改
     *
     * @PutMapping 请求方式为put http://localhost:8080/dept
     * @RequestBody 请求体  接收客户端发送的json格式数据
     */
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Employee employee) {
        try {
            if (employee.getId() == null) {
                employeeService.add(employee);
            } else {
                employeeService.update(employee);
            }
            return new AjaxResult();//用无参的表示成功
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "操作失败");
        }
    }

    /**
     * 根据id删除
     *
     * @DeleteMapping 请求方式为delete http://localhost:8080/dept/1
     */
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable("id") Long id) {
        try {
            employeeService.deleteById(id);
            return new AjaxResult();//用无参的表示成功
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "操作失败");
        }
    }

    /**
     * 批量删除
     */
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try{
            employeeService.batchDelete(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败！");
        }
    }
}
